package com.supermap.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XMLManager {

    /**
     * @Author zhangming
     * @Description TODO
     * @Date 2020/3/25 22:44
     * @Param []
     * @return 
     **/
    public XMLManager() {
    }

    /**
     * @return
     * @Author zhangming
     * @Description TODO
     * @Date 2020/3/24 0:05
     * @Param [xmlfile]
     **/
    public XMLManager(String xmlfile) {
        XMLWriter writer = null;
        File file = new File(xmlfile);
        if ( !file.exists() ) {
            // 创建Document对象，代表整个xml文档
            Document document = DocumentHelper.createDocument();
            // 创建根节点rss
            Element rss = document.addElement("warnings");
            rss.setText("");

            // 设置生成xml文件格式(利用OutputFormat的creatPrettyPrint()方法设置)
            OutputFormat format = OutputFormat.createPrettyPrint();
            // 设置编码格式
            format.setEncoding("GBK");
            // 生成文件

            try {
                // 先创建XMLWriter对象
                writer = new XMLWriter(new FileOutputStream(xmlfile), format);
                // 设置是否转义符号，默认值为true，代表转义
                writer.setEscapeText(false);
                // 利用XMLWriter的write方法传入Document类型对象
                writer.write(document);
                writer.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void write(String xmlfile, String triggerid, String appname, String apptype,String appaddress,String description) throws IOException {

        // 创建解析器对象
        SAXReader saxReader = new SAXReader();
        // 得到document
        Document document = null;

        try {
            File file = new File(xmlfile);
            document = saxReader.read(file);
            // 得到根节点
            Element root = document.getRootElement();

            // 在根节点下面添加元素
            Element step = root.addElement("warning");
            step.addAttribute("triggerid: ", triggerid);

            // 在step下面创建元素
            Element appnameElement = step.addElement("appname");
            Element appatypeElement = step.addElement("appadtype");
            Element contentElement = step.addElement("description");
            Element appaddressElement = step.addElement("appaddress");

            appnameElement.setText(appname);
            appatypeElement.setText(apptype);
            contentElement.setText(description);
            appaddressElement.setText(appaddress);

            // 回写xml
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlfile), format);
            xmlWriter.write(document);
            xmlWriter.close();

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * @return long
     * @Author zhangming
     * @Description TODO
     * @Date 2020/3/24 0:04
     * @Param [xmlfile]
     **/
    @SuppressWarnings("rawtypes")
    public String reader(String triggerid, String xmlfile) {
        String description = null;
        // 创建解析器对象
        SAXReader saxReader = new SAXReader();
        // 得到document
        Document document = null;

        try {
            File file = new File(xmlfile);
            document = saxReader.read(file);
            // 得到根节点
            Element root = document.getRootElement();

            Element element;
            for (Iterator i = root.elementIterator("warning"); i.hasNext(); ) {
                element = (Element) i.next();
                long id = Long.parseLong(element.attributeValue("triggerid"));
                System.out.println("triggerid: " + triggerid);
                if ( id == Long.parseLong(triggerid) ) {
                    List<Element> childElement = element.elements();
                    for (Element item : childElement) {
                        if(item.getName().equalsIgnoreCase("description")){
                            description =  item.getTextTrim();
                            break;
                        }
                    }
                    break;
                }
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return description;
    }


    @SuppressWarnings("rawtypes")
    public void removeElement(String triggerid, String xmlpath) {
        // TODO Auto-generated method stub
        // 创建解析器对象
        SAXReader saxReader = new SAXReader();
        // 得到document
        Document document = null;

        try {
            File file = new File(xmlpath);
            document = saxReader.read(file);
            // 得到根节点
            Element root = document.getRootElement();

            Element element;
            for (Iterator i = root.elementIterator("warning"); i.hasNext(); ) {
                element = (Element) i.next();
                long id = Long.parseLong(element.attributeValue("triggerid"));
                System.out.println("triggerid :" + triggerid);
                if ( id == Long.parseLong(triggerid) ) {
                    System.out.println("移除节点返回：" + root.remove(element));
                    break;
                }
            }

            // 回写xml
            OutputFormat format = OutputFormat.createPrettyPrint();

            try {
                XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(xmlpath), format);
                xmlWriter.write(document);
                xmlWriter.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
